package net.csiit.tools.fileserver.common.util;

import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String MONTH_PATTERN = "yyyy-MM";

    public static String getTodayString() {
        return formatDate(new Date());
    }

    public static String getThisMonthString() {
        return format(MONTH_PATTERN, new Date());
    }

    public static String format(String pattern, Date date) {
        return new SimpleDateFormat(pattern).format(date);
    }

    public static String formatDate(@NotNull Date date) {
        return new SimpleDateFormat(DATE_TIME_PATTERN).format(date);
    }

    public static Date addDays(Date date1, Integer days) {
        if (days == null || days == 0) {
            return date1;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        calendar.add(Calendar.DAY_OF_YEAR, days);
        return calendar.getTime();
    }

    /**
     * 获取昨天的 23:59:59:999
     * @return
     */
    public static Date getLastTimeBeforeToday() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return calendar.getTime();
    }


    public static Date getLastTimeBeforeTomorrow() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    public static Date getLastTimeOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    public static Date parseDate(String date) {
        String[] patterns = {"yyyy-MM-dd","yyyy-M-dd","yyyy-M-d", "yyyy-MM-d",
                "yyyy.MM.dd","yyyy.M.dd","yyyy.M.d", "yyyy.MM.d"};
        for (String s : patterns) {
            try {
                return new SimpleDateFormat(s).parse(date);
            } catch (Exception e) {
            }
        }

        return null;
    }

    public static String getCurrentMonth() {
        return new SimpleDateFormat("yyyy-MM").format(new Date());
    }


}
